import def from '../../define'
import util from '../../util'
import timer from '../../timer'
import { popupToast } from '../../ui-util'

const makeupPlugin = require('../../pfMakeupPlugin/index')

const status = makeupPlugin.getStatusTable()
const app = getApp()

let pfMakeup
let that
let camera
let cameraFrameListener
let photoModeRawFrame
const log = t => getApp().globalData.logger.log('[tryOn]' + t)

let forceOpenCameraTimeout
let _camerafps
let _renderfps
let printFpsLoop

Page({
  data: {
    offscreenCanvasWidth: 0,
    offscreenCanvasHeight: 0,
    pixalRatio: 1,
    canvasWidth: 540,
    canvasHeight: 960,
    frameSize: 'large',
    canvasHidden: false,
    enableCamera: true,
    renderingCanvasId: 'tryOnCanvas',
    makeupCameraId: 'tryOnCameraId',
    cameraFacing: 'front',
    skuTypeList: {
      types: [],
      selected: null // {type: '', name: ''}
    },
    productList: {
      products: [],
      selectedGuid: ''
    },
    lookDetail: {
      isShow: false,
      look: {}
    },
    skuList: {
      skus: [],
      palettesMap: {},
      patternsMap: {},
      patternGuids: []
    },
    tryOnList: def.initTypesMap(null), // key: type, value: {productGuid: '', skuGuid: '', paletteGuid: '', patternGuid: ''}
    intensities: {},
    skuTypeIntensityState: {
      isSupport: false,
      isEnabled: false,
      sliderValue: 0
    },
    isCompareEnabled: false,
    supportScaleTypes: def.SCALE_TYPES,
    scaleType: 'CENTER_CROP',
    isSDKReady: false,
    isShotBlocked: false,
    featureSlider: {
      pickerOptions: def.SUPPORT_FEATURE_LIST,
      values: {
        zoomRatio: 0,
        comparePosition: 5,
        skinSmooth: 0,
        faceReshape: 0,
        enlargeEye: 0
      }
    },
    frameInfo: '',
    eyeTypeIndex: 11,
    isVip: false,
    goodsArr:[647729224878,638453613583,639126739883,648135125314,638453841882,638454201898,643517769708,651311392532],
    eyelashImgArr:[
      {
        name:"轻欧混血",
        imgURL:"https://img.alicdn.com/imgextra/i3/4161056916/O1CN01zGA1PJ20xZu3DNfJ5_!!4161056916.png"
      },
      {
        name:"日系清透",
        imgURL:"https://img.alicdn.com/imgextra/i3/4161056916/O1CN01VBYiXZ20xZtwSRocx_!!4161056916.png"
      },
      {
        name:"闪光少女",
        imgURL:"https://img.alicdn.com/imgextra/i1/4161056916/O1CN01qOWxLl20xZtx3p1sk_!!4161056916.png"
      },
      {
        name:"猫系女友",
        imgURL:"https://img.alicdn.com/imgextra/i2/4161056916/O1CN01mBJ3De20xZu5Yw9JI_!!4161056916.png"
      },
      {
        name:"纯欲森林",
        imgURL:"https://img.alicdn.com/imgextra/i1/4161056916/O1CN01wKe81Q20xZtqDEkr0_!!4161056916.png"
      },
      {
        name:"微醺月光",
        imgURL:"https://img.alicdn.com/imgextra/i2/4161056916/O1CN01zO43f820xZu7FGHl7_!!4161056916.png"
      },
      {
        name:"仲夏浅茶",
        imgURL:"https://img.alicdn.com/imgextra/i1/4161056916/O1CN013emujV20xZu2CAUUW_!!4161056916.png"
      },
      {
        name:"午夜探戈",
        imgURL:"https://img.alicdn.com/imgextra/i3/4161056916/O1CN01924c7o20xZu4oD60U_!!4161056916.png"
      }
    ]
  },


  productClick: async function(e){
    // my.alert({
    //   content:JSON.stringify(`产品阐述${e.currentTarget.dataset.productGuid}---${e.currentTarget.dataset.skuGuid}`)
    // })

    this.setData({ eyeTypeIndex: e.currentTarget.dataset.index});

    let productGuid = e.currentTarget.dataset.productGuid;
    let skuGuid = e.currentTarget.dataset.skuGuid
    
    pfMakeup.applyMakeupBySkus([{ productGuid, skuGuid }], callback => {
      //my.alert({content:`callback：${callback}`});
    });

    getApp().dataMd(30+parseInt(e.currentTarget.dataset.index),`第${e.currentTarget.dataset.index}款睫毛试戴参与人数`)

  },

  createForceOpenCameraTimeout: function() {
    forceOpenCameraTimeout = setTimeout(() => {
      this.restartCameraFrameListener(() => {})
    }, 1000)
  },

  clearForceOpenCameraTimeout: function() {
    if (forceOpenCameraTimeout) {
      clearTimeout(forceOpenCameraTimeout)
      forceOpenCameraTimeout = null
    }
  },

  onLoad: function() {
    // log('[onLoad]')

    //my.alert({content:`是否会员：${app.TaobaoMember}`});

    this.setData({isVip:app.TaobaoMember})

    // if(app.TaobaoMember){
      
    // }

    that = this

    // eslint-disable-next-line new-cap
    _camerafps = new timer()
    // eslint-disable-next-line new-cap
    _renderfps = new timer()

  },

  //非会员入会
  joinVip(){
    my.call('navigateToOutside',{
      url:
        'https://market.m.taobao.com/app/sj/member-center-rax/pages/pages_index_index?wh_weex=true&source=ShopSelfUse&sellerId=2210925259336'
      },(res)=>{ 
    })
  },

  //跳转商品
  productDetails(){

    //my.alert({content:'商详'})
    if(this.data.eyeTypeIndex == 11){
      my.showToast({content:'请先选择一款睫毛试戴吧~'});
      return
    }

    my.tb.openDetail ({
      itemId: this.data.goodsArr[this.data.eyeTypeIndex].toString(),
      success: (res) => {
        //my.alert({ content: "success" });
        getApp().dataMd(40+parseInt(this.data.eyeTypeIndex),`点击查看第${this.data.eyeTypeIndex}个商品的人数，商品id为${this.data.goodsArr[this.data.eyeTypeIndex]}`)
      },
      fail: (res) => {
        //my.alert({ content: "fail - " + res.error });
      },
    });d
  },

  // 下单
  placeAnOrder(){
    //my.alert({content:'下单'})
    my.tb.confirmCustomOrder({
      data:{
        'itemId':this.data.goodsArr[this.data.eyeTypeIndex].toString(),
        'skuId':'',   
        'quantity':1,
        'customization':{}  
      },
      success:function(e) {   
        //my.alert({title: 'success ',content:JSON.stringify(e)});
        getApp().dataMd(50+parseInt(this.data.eyeTypeIndex),`点击下单第${this.data.eyeTypeIndex}个商品的人数，商品id为${this.data.goodsArr[this.data.eyeTypeIndex]}`)
      },
      fail:function(e) {  my.alert({  title: 'fail ',  content: JSON.stringify(e)  })  }  
    });
  },

  //加入购物车
  addCat(){
    //my.alert({content:'加入购物车'})
    if(this.data.eyeTypeIndex == 11){
      my.showToast({content:'请先选择一款睫毛试戴吧~'});
      return
    }
    my.tb.showSku({  
      itemId: this.data.goodsArr[this.data.eyeTypeIndex].toString(),   
      success: (result) => {  
      // 这里把用户选中数据返回给业务方处理，添加到小购物车。和天猫超市类似，选中宝贝也会同步在手淘购物车展示  
        // my.showToast({  
        //     content: 'showSku ' + JSON.stringify(result)  
        // });  

        getApp().cloud.function.invoke('client',{productId:this.data.goodsArr[this.data.eyeTypeIndex]},'goodsPurchased').then(res => {
          if(res.code == 200){
            //my.alert({content:"加购接口调用成功！"})
          }
        });

        getApp().dataMd(60+parseInt(this.data.eyeTypeIndex),`点击加购第${this.data.eyeTypeIndex}个商品的人数，商品id为${this.data.goodsArr[this.data.eyeTypeIndex]}`)

      },
      fail: result => {
           //my.alert({ content: "fail" + JSON.stringify(result) })
      }, 
    });
  },

  initTryOnButtons: function() {
    this.setData({
      skuTypeList: {
        ...this.data.skuTypeList,
        types: app.globalData.featureSetting.enableAllFeatures ? def.ALL_MAKEUP_TYPES : def.SUPPORT_LIST
      }
    })
    //my.alert({content:JSON.stringify(this.data.skuTypeList)})
  },

  canvasOnReady() {
    log('[canvasOnReady]')
    my.showLoading()
    const systemInfo = my.getSystemInfoSync()
    const makeupPlugin = require('../../pfMakeupPlugin/index')
    pfMakeup = makeupPlugin.getPfMakeup()
    this.setData(
      {
        pixelRatio: systemInfo.pixelRatio
      },
      () => {
        const timeoutMs = (getApp().globalData.systemInfo.platform === 'Android') ? 0 : 500
        setTimeout(() => {
          my.createCanvas({
            id: this.data.renderingCanvasId,
            success: c => {

              log(`createCanvas: ${JSON.stringify(c)}`);

              pfMakeup.init({
                perfectLib: app.globalData.perfectLib,
                canvas: c,
                callback: this.initCallback,
                enableSkia: true
              })

            }
          })
        }, timeoutMs)
      }
    )
  },

  onReady: function() {
    log('[onReady]')
  },
  onShow: function() {
    this.setData({
      isShotBlocked: false
    })
    this.initTryOnButtons()

    if (!that.data.enableCamera && photoModeRawFrame) {
      // Android-Taobao requires time to remount canvas when onShow
      app.globalData.systemInfo.platform === 'Android' && that.processCanvasTilCanvasMount()
    } else {
      cameraFrameListener && cameraFrameListener.start()
      this.createForceOpenCameraTimeout()
    }
  },
  
  onHide: function() {
    cameraFrameListener && cameraFrameListener.stop()
  },

  onUnload: function() {
    pfMakeup.unInit()
    that.clearForceOpenCameraTimeout()
    pfMakeup = null
    cameraFrameListener = null
    camera = null
    photoModeRawFrame = null
    clearInterval(printFpsLoop)
    printFpsLoop = null
  },

  processCanvasTilCanvasMount: function() {
    my.showLoading()
    setTimeout(() => {
      pfMakeup.processFrame(photoModeRawFrame, true, that.processPhotoFrameCallback)
    }, 3000)
  },


  initCallback: function(statusCode, extraInfo) {
    log('pfMakeup initcallback:' + statusCode)
    that.onCameraModeClick();
    that.productInformation();
    my.hideLoading()
    if (statusCode !== status.STATUS_SUCCESS) {
      my.alert({
        content: 'Init failed, statusCode=' + statusCode,
        success: () => my.navigateBack()
      })
    }

  },

  productInformation: async function(){

    pfMakeup.getListByEffect('eyelashes', 0, callback => {

      //my.alert({content: JSON.stringify(callback)})

      this.setData({
        productList:callback
      })

    })

  },

  


  




  // setInitData: function() {
  //   log('[setInitData]')
  //   const intensities = pfMakeup.getIntensities()
  //   this.setData({
  //     isSDKReady: true,
  //     intensities,
  //     featureSlider: {
  //       ...this.data.featureSlider,
  //       values: {
  //         ...this.data.featureSlider.values,
  //         skinSmooth: intensities.skinSmooth,
  //         faceReshape: intensities.faceReshape,
  //         enlargeEye: intensities.enlargeEye
  //       }
  //     }
  //   })

  //   //my.alert({content:JSON.stringify(this.data.featureSlider)})
  // },

  onCameraModeClick: function() {
    photoModeRawFrame = null
    this.setData(
      {
        enableCamera: true
      },
      () => {
        camera = my.createCameraContext(this.data.makeupCameraId)
        cameraFrameListener = camera.onCameraFrame(frame => {
          _camerafps.end()
          // [Workaround][Android 9.7.1] If frame start normally, stop force start timeout
          this.clearForceOpenCameraTimeout()
          pfMakeup && pfMakeup.processFrame(frame, false, that.processCameraFrameCallback)
        })
        cameraFrameListener.start()
        // [Workaround][Android 9.7.1] Force open camera frame listener when frame didn't start to send correctly.
        this.createForceOpenCameraTimeout()
      }
    )
  },

  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'wosado睫毛试戴体验',
      desc: '一秒变身',
      path: `pages/index/index?shareMenber=${getApp().userInfoX.nickName}`,
    };
  }
  
})
